<template>
    <div class="gradeList">
        <div class="header">
            <el-button type="primary" @click="handleAdd">添加老师信息</el-button>
            <div class="upload">
                <input type="file" id="file" @change="selectFile" style="display: none;">
                <el-button type="primary">
                    <label for="file">
                        批量添加
                        <!-- <el-button type="primary" @click="uploadFile">批量添加</el-button> -->
                    </label>
                </el-button>
            </div>
            <el-dialog title="用户信息" :visible.sync="dialogAddVisible">
                <div class="dialogAdd">
                    <FormAdd btnMsg="添加老师" @success="doNext"></FormAdd>
                </div>
            </el-dialog>
            <el-input placeholder="输入关键字搜索" v-model="search" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="findUser"></el-button>
            </el-input>
            <div class="download">
                <el-button type="primary" @click="download">下载</el-button>
            </div>
        </div>
        <el-table :data="userList" height="520" style="width: 100%;padding: 20px;margin: 0 auto;">
            <el-table-column prop="teacherIco" label="证件照" width="150" show-overflow-tooltip align="center">
                <template slot-scope="scope">
                    <img v-if="!scope.row.teacherIco" style="width: 100px; height: 100px; border-radius: 50%;"
                        src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                    <el-image v-else style="width: 100px; height: 100px; border-radius: 50%;"
                        :src="scope.row.teacherIco"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="teacherName" label="姓名" width="120" show-overflow-tooltip align="center">
            </el-table-column>
            <el-table-column prop="teacherPhone" label="电话" width="230" show-overflow-tooltip align="center">
            </el-table-column>
            <el-table-column prop="teacherId" label="工号" width="230" show-overflow-tooltip align="center">
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <div style="display: flex;flex-direction: row;justify-content: center;">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修改用户信息弹框 -->
        <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
            <el-form :model="editInfo" :rules="rules" ref="editForm">
                <div
                    style="display: flex; flex-direction: row; justify-content: space-around; align-items: center; width: 100%; margin: 5px auto;">
                    <input type="file" multiple id="image" @change="select" style="display: none;">
                    <label for="image">
                        <img v-if="!editInfo.teacherIco" class="img"
                            src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                        <el-image v-else class="img" :src="editInfo.teacherIco" />
                    </label>
                    <el-button type="primary" @click="Submit(editInfo.id)">确认更换</el-button>
                </div>
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="teacherName">
                    <el-input v-model="editInfo.teacherName" autocomplete="off" placeholder="姓名"></el-input>
                </el-form-item>

                <el-form-item label="工号" :label-width="formLabelWidth" prop="teacherId">
                    <el-input v-model="editInfo.teacherId" autocomplete="off" placeholder="工号"></el-input>
                </el-form-item>

                <el-form-item label="电话" :label-width="formLabelWidth" prop="teacherPhone">
                    <el-input v-model="editInfo.teacherPhone" autocomplete="off" placeholder="电话"></el-input>
                </el-form-item>

                <el-form-item label="班级" :label-width="formLabelWidth" prop="classId">
                    <el-select v-model="editInfo.classId" placeholder="请选择班级" style="float: left;width: 100%;">
                        <el-option v-for="item in option" :key="item.id" :label="item.className" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程" :label-width="formLabelWidth" prop="courseId">
                    <el-input v-model="editInfo.id" autocomplete="off" placeholder="课程"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeInfo('editForm')">确 定</el-button>
            </div>
        </el-dialog>

        <div class="pages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>
</template>
  
<script>
import FormAdd from '../FormAdd.vue';
import * as imageConversion from 'image-conversion';

export default {
    name: 'GradePage',
    components: {
        FormAdd,
    },
    data() {
        return {
            msg: '教师管理',
            schoolId: 1,
            userList: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            // 搜索
            search: '',
            // 编辑
            editInfo: {},
            dialogFormVisible: false,
            dialogAddVisible: false,
            formLabelWidth: '120px',
            // 头像
            fileData: '',
            rules: {
                teacherName: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' }
                ],
                teacherPhone: [
                    { required: true, message: '电话不能为空', trigger: 'blur' }
                ],
                teacherId: [
                    { required: true, message: '工号不能为空', trigger: 'blur' }
                ],
                classId: [
                    { required: true, message: '班级不能为空', trigger: 'blur' }
                ],
                courseId: [
                    { required: true, message: 'gradeId不能为空', trigger: 'blur' }
                ],
            },
            option: []
        }
    },
    methods: {
        // 编辑
        async handleEdit(index, row) {
            console.log(index, row);
            // delete row.teacherIco
            this.editInfo = { ...row };
            this.dialogFormVisible = true;
        },
        // 
        changeInfo(form) {
            this.$refs[form].validate((valid) => {//表单校验
                if (valid) {//valid表示验证是否通过，返回值为布尔类型
                    this.dialogFormVisible = false;
                    this.$axios.post('http://39.105.215.62:8100/teacher/updateTeacher', { ...this.editInfo, teacherIco: null })
                        .then(async (res) => {
                            console.log(res);
                            if (res.code == 200) {
                                await this.getList();
                                this.$message({
                                    message: res.msg,
                                    type: 'success'
                                });
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                } else {
                    console.log('表格不能为空!!');
                    return false;
                }
            });
        },
        handleDelete(index, row) {
            console.log(index, row.id);
            // 提示信息
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            })
                .then(async () => {
                    let fd = new FormData();
                    fd.append('id', row.id);
                    let res = await this.$axios.post('http://39.105.215.62:8100/teacher/deleteTeacher', fd);
                    console.log(res);
                    if (res.code == 200) {
                        await this.getList();
                        this.$message({
                            type: 'success',
                            message: res.msg
                        });
                        if (this.userList.length == 0 && this.currentPage > 1) {
                            this.currentPage = this.currentPage - 1;
                            await this.getList();
                        }
                    }
                })
        },
        handleAdd() {
            this.dialogAddVisible = true;
        },
        doNext(msg) {
            if (msg) {
                this.dialogAddVisible = false;
                this.getList();
            }
        },
        async getList() {
            let res = await this.$axios.post(`http://39.105.215.62:8100/teacher/findTeachers?pageNum=${this.currentPage}&pageSize=${this.pageSize}`, { schoolId: this.schoolId })
            console.log(res);
            if (res.code == 200) {
                this.total = res.data.total;
                this.userList = res.data.records.map(item => {
                    if (item.teacherIco) {
                        let string = item.teacherIco + ''
                        let starti = string.indexOf('image/');
                        let endi = string.indexOf('base64/');
                        return { ...item, teacherIco: `data:${item.teacherIco.substring(starti, endi)};base64,${item.teacherIco.substring(endi + 6)}` }
                    } else {
                        return item;
                    }
                });
            }
        },
        async handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val
            await this.getList();
        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            await this.getList();
        },
        async findUser() {
            // if (this.search == '') {
            //     this.getList();
            //     this.$message.error('请输入关键字进行查找!')
            // }
            // else {
            //     let res = await this.$axios.post('/search', { keyWord: this.search });
            //     console.log(res);
            //     this.total = res.total;
            //     this.userList = res.List;
            //     if (res.total == 0) {
            //         this.$message.error(res.msg)
            //     } else {
            //         this.$message.success(res.msg)
            //     }
            //     this.search = '';
            // }
            if (this.search == '') {
                await this.getList();
                this.$message.error('请输入关键字进行查找!')
            }
            else {
                let res = await this.$axios.post('/search', { keyWord: this.search });
                console.log(res);
                this.total = res.total;
                this.userList = res.List;
                if (res.total == 0) {
                    this.$message.error(res.msg)
                } else {
                    this.$message.success(res.msg)
                }
                this.search = '';
            }
        },
        async Submit(id) {
            console.log(this.fileData);
            console.log(id);
            if (this.fileData) {
                let res = await this.$axios.post(`http://39.105.215.62:8100/teacher/addTeacherIco`, { id: id, ico: this.fileData });
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('图片上传成功!')
                    await this.getList()
                } else {
                    this.$message.error('图片上传失败!')
                }
                this.fileData = ''
            } else {
                this.$message.error('请选择图片!')
            }
        },
        ReadData(file) {
            console.log(file.type);
            const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
            const isSize = file.size / 1024 < 64;
            if (!isJpgOrPng) {
                this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
                return false;
            }
            return new Promise((resolve, rej) => {
                // 小于64kb 不压缩
                if (isSize) {
                    var reader = new FileReader();
                    reader.readAsDataURL(file);    // 解析成base64格式
                    reader.onload = async function () {
                        // console.log(this.result); // 解析后的数据
                        resolve(this.result);
                    }
                }
                // 压缩到64KB,这里的64就是要压缩的大小,可自定义
                imageConversion.compressAccurately(file, 64).then((res) => {
                    console.log(res);
                    var reader = new FileReader();
                    reader.readAsDataURL(res);    // 解析成base64格式
                    reader.onload = async function () {
                        // console.log(this.result); // 解析后的数据
                        resolve(this.result);
                    }
                });
            })
        },
        async select(e) {
            let fileList = e.target.files;
            this.fileData = await this.ReadData(fileList[0]);
            console.log(this.fileData);
        },
        async selectFile(e) {
            let fileList = e.target.files;
            let fd = new FormData();
            fd.append('file', fileList[0]);
            fd.append('schoolId', this.schoolId);

            let res = await this.$axios.post('http://39.105.215.62:8100/teacher/uploadTeacherModel', fd);
            console.log(res);
            if (res.code == 200) {
                this.$message.success('文件上传成功!')
                await this.getList();
            }
            // this.fileData = fd;
            // console.log(this.fileData);
        },
        async uploadFile() {
            console.log(1);
            let res = await this.$axios.post('http://39.105.215.62:8100/teacher/uploadTeacherModel', this.fileData);
            console.log(res);
            if (res.code == 200) {
                await this.getList();
            }
        },
        download() {
            this.$axios.get('http://39.105.215.62:8100/teacher/downloadTeacherModel', {
                responseType: 'blob'
            }).then(res => {
                console.log(res);
                const blob = new Blob([res], { type: 'application/xlsx' });
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                let d = new Date()
                a.download = `文件下载${d.getTime()}.xlsx`;
                a.click()
                URL.revokeObjectURL(a.href)
                a.remove()
            });
        },
        downloadError() {
            this.$axios.get('http://39.105.215.62:8100/teacher/downloadErrorTeacherModel', {
                responseType: 'blob'
            }).then(res => {
                console.log(res);
                const blob = new Blob([res], { type: 'application/xlsx' });
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                let d = new Date()
                a.download = `文件下载${d.getTime()}.xlsx`;
                a.click()
                URL.revokeObjectURL(a.href)
                a.remove()
            });
        },
        async getClassList() {
            let result = await this.$axios.post(`http://39.105.215.62:8200/class/selectClasses?pageNum=1&pageSize=10`, { gradeId: 0, schoolId: this.schoolId });
            console.log(result);
            this.option = result.data.records;
        },
    },
    // 生命周期函数--钩子函数一般在初始化页面完成后，再对DOM节点进行相关操作
    async mounted() {
        console.log(this.$route.query);
        this.$emit("transfer", this.msg);
        this.schoolId = JSON.parse(sessionStorage.getItem('info')).schoolId;
        await this.getList();
        await this.getClassList()
        // this.downloadError()
    }
}
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.header {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid #ccc;
    padding: 5px;
}

.input-with-select {
    width: 400px;
}

.dialogAdd {
    display: flex;
    justify-content: center;
    align-items: center;
}

.pages {
    margin: 20px auto;
}

.img {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    cursor: pointer;
}
</style>
  